package com.zeny.express.framework.mq.activemq;

import javax.jms.JMSException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zeny.express.framework.mq.AbstractMqClient;
import com.zeny.express.framework.mq.MqCallback;
import com.zeny.express.framework.shared.serializer.JsonSerializer;

/**
 * 
 * @author KenQiu
 *
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class ActiveMqClient<T> extends AbstractMqClient<T> {
	protected final static Logger LOGGER = LoggerFactory
			.getLogger(ActiveMqClient.class);

	protected ActiveMqTemplate mqTemplate;
	
	public ActiveMqClient() {
		this(true);
	}

	@SuppressWarnings("deprecation")
	public ActiveMqClient(boolean syncpoint) {
		dataBinarySerializer = new JsonSerializer<T>(true, getDataClass());
		dataTextSerializer = new JsonSerializer<T>(false, getDataClass());

		mqTemplate = new ActiveMqTemplate();

		//TODO:支持事务配置
		if (syncpoint) {
		}
	}

	public T get() {
		return mqTemplate.execute(mqPool, new MqCallback<T, ActiveMqQueueHandler>() {
			@Override
			public T doInMq(ActiveMqQueueHandler handler) throws Exception {
				byte[] bytes = handler.receive();

				if(bytes == null)
				{
					return null;
				}
				
				Object value = getDataSerializer(dataFormat).deserialize(bytes);
				
				return (T) value;
			}
		});
	}

	public void put(final T data) {
		final byte[] bytes = getDataSerializer(dataFormat).serialize(data);

		mqTemplate.execute(mqPool, new MqCallback<T, ActiveMqQueueHandler>() {
			@Override
			public T doInMq(ActiveMqQueueHandler handler) throws JMSException {
				 handler.send(bytes);

				return data;
			}
		});
	}
}
